package com.jikangjun.disk.login.service.impl;

import com.jikangjun.disk.login.entity.MenuLevelEntity;
import com.jikangjun.disk.login.repository.LoginDao;
import com.jikangjun.disk.login.service.LoginService;
import com.jikangjun.disk.mybatis.entity.PtMenuEntity;
import com.jikangjun.disk.mybatis.entity.PtUserEntity;
import com.jikangjun.disk.spring.annotation.LogPoint;
import com.jikangjun.disk.spring.security.UserDiskEntity;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class LoginServicelmpl implements LoginService {

    @Resource
    private LoginDao loginDao;

    @LogPoint
    @Override
    public PtUserEntity queryUserInfoByName(String username) {
        return loginDao.queryUserInfoByName(username);
    }

    @Override
    public List<PtMenuEntity> queryMenuList() {
        String lang = LocaleContextHolder.getLocale().toString();
        UserDiskEntity userDiskEntity  = (UserDiskEntity) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String userUuid = userDiskEntity.getUserUuid();
        return loginDao.queryMenuList(lang,userUuid);
    }

    @Override
    public List<MenuLevelEntity> queryMenuListLevel() {
        String lang = LocaleContextHolder.getLocale().toString();
        UserDiskEntity userDiskEntity  = (UserDiskEntity) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        String userUuid = userDiskEntity.getUserUuid();


        List<PtMenuEntity> ptMenuEntityList = loginDao.queryMenuList(lang, userUuid);
        //转变级菜单
        List<MenuLevelEntity> levelEntityList = new ArrayList<>();
        for(PtMenuEntity ptMenuEntity :  ptMenuEntityList){
            levelEntityList.add(new MenuLevelEntity(ptMenuEntity));
        }
        //寻找父亲菜单
        List<MenuLevelEntity> sysEntityList = new ArrayList<>();
        boolean findFlag = false;
        for (MenuLevelEntity level1:levelEntityList){
            findFlag = false;
            for(MenuLevelEntity parent:levelEntityList){

                if(parent.getMenuId().equals(level1.getParentId())){
                    findFlag = true;
                    parent.addChild(level1);
                    break;
                }
            }
            if(!findFlag){
                sysEntityList.add(level1);
            }
        }
        return sysEntityList;
    }

    @Override
    public List<String> queryPermissionList(String userUuid) {

        return loginDao.queryPermissionList(userUuid);
    }
}
